package com.yuelan.order.config;

import org.springframework.amqp.core.*;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;


/**
 * @description:
 * @Author: ZhaoYi
 * @date: 24-6-27 1:04
 */
//@Configuration
public class RabbitConfig {

    // 延迟交换机
    public static final String ORDER_DELAY_EXCHANGE = "order.delay.exchange";
    // 延迟队列
    public static final String ORDER_DELAY_QUEUE = "order.delay.queue";
    // 延迟队列路由Key
    public static final String ORDER_DELAY_QUEUE_ROUTING_KEY = "order.delay.queue.routingkey";
    // 死信交换机
    public static final String ORDER_DEAD_LETTER_EXCHANGE = "order.dead.letter.exchange";
    // 死信队列
    public static final String ORDER_DEAD_LETTER_QUEUE = "order.dead.letter.queue";
    // 死信队列路由Key
    public static final String ORDER_DEAD_LETTER_QUEUE_ROUTING_KEY = "order.dead.letter.routingkey";


    // 声明延迟交换机
    @Bean("orderDelayExchange")
    public DirectExchange orderDelayExchange() {
        return new DirectExchange(ORDER_DELAY_EXCHANGE);
    }

    // 声明死信交换机
    @Bean("orderDeadLetterExchange")
    public DirectExchange orderDeadLetterExchange() {
        return new DirectExchange(ORDER_DEAD_LETTER_EXCHANGE);
    }

    // 声明延迟队列，不设置消息TTL存活时间，并绑定到对应的死信交换机
    @Bean("orderDelayQueue")
    public Queue orderDelayQueue() {
        Map<String, Object> args = new HashMap<>();
        // x-dead-letter-exchange 声明队列绑定的死信交换机
        args.put("x-dead-letter-exchange", ORDER_DEAD_LETTER_EXCHANGE);
        // x-dead-letter-routing-key 声明队列的死信路由Key
        args.put("x-dead-letter-routing-key", ORDER_DEAD_LETTER_QUEUE_ROUTING_KEY);
        return QueueBuilder.durable(ORDER_DELAY_QUEUE).withArguments(args).build();
    }

    // 声明延迟队列的绑定关系
    @Bean
    public Binding delayBinding(@Qualifier("orderDelayQueue") Queue queue,
                                @Qualifier("orderDelayExchange") DirectExchange exchange) {
        return BindingBuilder.bind(queue).to(exchange).with(ORDER_DELAY_QUEUE_ROUTING_KEY);
    }

    // 声明死信队列
    @Bean("orderDeadLetterQueue")
    public Queue orderDeadLetterQueue() {
        return new Queue(ORDER_DEAD_LETTER_QUEUE);
    }

    // 声明死信队列的绑定关系
    @Bean
    public Binding deadLetterBinding(@Qualifier("orderDeadLetterQueue") Queue queue,
                                     @Qualifier("orderDeadLetterExchange") DirectExchange exchange) {
        return BindingBuilder.bind(queue).to(exchange).with(ORDER_DEAD_LETTER_QUEUE_ROUTING_KEY);
    }

}
